import axios from 'axios'
import { Loading, Message  } from 'element-ui'
import store from '@/store'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.baseURL = location.origin + '/dashen'
axios.defaults.timeout = 60000

axios.defaults.transformRequest = [function (data) {
  let ret = ''
  for (let it in data) {
   ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  return ret
}]

let loading;

// loading开始
const start_loading = () => {
    loading = Loading.service({
        lock: true,
        text: '正在加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
}

// loading结束
const end_loading = () => {
    loading.close()
}

// 添加请求拦截器
axios.interceptors.request.use( config => {
  start_loading()
  
  // 设置请求带userLoginToken
  let userLoginToken = localStorage.getItem('userLoginToken')
  if(userLoginToken) {
    config.headers.userLoginToken = userLoginToken
  }
  return config
}, error => {
  end_loading()
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use( response => {
  
  let { data } = response

  if (data.errCode == 200) {
    console.log('continue......[滴~滴] - 【你的小猴子已经准备就绪~~~~小怪兽嘻，大马猴来咯~~~】');
  } else {
    Message.error({ message: data.errMsg, offset: document.body.offsetHeight / 2 })
    if (data.errCode == 201) {
      store.dispatch('login_out')
    }
  }
  end_loading()
  return data
}, error => {
  end_loading()
  return Promise.reject(error);
})

